package server

import (
	"fmt"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql/db_live"
	"longmen/server/pkg/protobuf"
	"strings"

	"gorm.io/gorm"
)

type Server struct {
	protobuf.UnimplementedLiveServerServer
}

func (s *Server) Category() ([]*protobuf.SummaryCategory, error) {
	fName := "GetCategory"
	var liveBigCategoryArr []*protobuf.SummaryCategory
	liveBigCategoryArr = make([]*protobuf.SummaryCategory, 0)
	res, err := db_live.GetLiveCategoryParam(map[string]interface{}{"status": 1}, "sort, id")
	if err != nil {
		return nil, fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	resTop, err := db_live.GetLiveCategoryTopParam(map[string]interface{}{"status": 1}, "sort, id")

	for _, v := range resTop {
		liveBigCategory := new(protobuf.SummaryCategory)
		liveBigCategory.Id = uint32(v.Id)
		liveBigCategory.Name = v.Title
		liveBigCategory.Logo = v.Icon
		liveBigCategory.LogoSel = v.SecondIcon
		for _, l := range res {
			if l.Category == v.Id {
				liveBigCategory.SecondCategory = append(liveBigCategory.SecondCategory, &protobuf.Category{Id: uint32(l.Id), Name: l.Title, Logo: l.Icon})
			}
		}
		liveBigCategoryArr = append(liveBigCategoryArr, liveBigCategory)
	}
	return liveBigCategoryArr, nil
}

type Total struct {
	S int64
}

func Condition(table *gorm.DB, param map[string]interface{}, groupBy, order string, page, size int) {
	condition(table, param, groupBy, order, page, size)
}

func condition(table *gorm.DB, param map[string]interface{}, groupBy, order string, page, size int) *gorm.DB {
	if len(param) > 0 {
		for k := range param {
			if strings.ToLower(k) == "or" {
				if c, ok := param[k].([]interface{}); ok {
					if len(c) >= 2 {
						table.Where(fmt.Sprintf("(%v)", c[0]), c[1:]...)
					}
				}
				continue
			}
			if c, ok := param[k].(map[string]interface{}); ok {
				for k2, v2 := range c {
					if strings.ToLower(k2) == "between" {
						v3, ok := v2.([]interface{})
						if ok && len(v3) >= 2 {
							table.Where(fmt.Sprintf("%s %s ? and ?", k, k2), v3[0], v3[1])
						}
						continue
					}
					table.Where(fmt.Sprintf("%s %s ?", k, k2), v2)
				}
				continue
			}
			table.Where(fmt.Sprintf("%s = ?", k), param[k])
		}
	}
	if len(groupBy) > 0 {
		table.Group(groupBy)
	}
	if len(order) > 0 {
		table.Order(order)
	}
	if page > 0 && size > 0 {
		table.Limit(size).Offset((page - 1) * size)
	}
	return table
}
